package com.wfs.suanfa.jvm.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * @author: wfs
 * @Date: 2020/11/18 20:10
 * @Description:
 */
public class T004_ClassLoaderMyselfe extends ClassLoader{
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File f=new File("D:\\spring\\shenzhou-goodspayment-broker\\target\\test-classes\\Test.class");
        try {
            FileInputStream fis = new FileInputStream(f);
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int b=0;
            while ((b=fis.read()) !=0){
                baos.write(b);
            }
            byte[] bytes = baos.toByteArray();
            baos.close();
            fis.close();
            return defineClass(name,bytes,0,bytes.length);
        }catch (Exception e){
            e.printStackTrace();
        }
        return super.findClass(name);

    }

    public static void main(String[] args) throws Exception {
        ClassLoader l=new T004_ClassLoaderMyselfe();

        Class aClass = l.loadClass("TestMain");
        Object o = aClass.newInstance();
        Method[] methods = o.getClass().getMethods();
        System.out.println(l.getClass().getClassLoader());
        System.out.println(l.getParent());

    }
}
